package com.wsg.dep.util.office;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Stack;

/**
 * @className: PdfGenerator
 * @author: 承泽
 * @date: 2025/3/25 11:46
 * @description:
 */
public class PdfGenerator implements ReportGenerator {
    private static final int DEFAULT_FONT_SIZE = 12;
    private static final Rectangle DEFAULT_PAGE_SIZE = PageSize.A4;
    private static final float DEFAULT_MARGIN = 50;
    private static final float DEFAULT_PARAGRAPH_SPACING_BEFORE = 4;
    private static final float DEFAULT_PARAGRAPH_SPACING_AFTER = 4;
    private static final float DEFAULT_TABLE_SPACING_BEFORE = 4;
    private static final float DEFAULT_TABLE_SPACING_AFTER = 4;
    // 自定义蓝色（45A4FF 对应的 RGB：69, 164, 255）
    private static final BaseColor CUSTOM_BLUE = new BaseColor(69, 164, 255);

    private Document document;
    private PdfWriter writer;
    private final int fontSize;



    public PdfGenerator() {
        this(DEFAULT_FONT_SIZE);
    }

    public PdfGenerator(int fontSize) {
        this.fontSize = fontSize;
    }

    @Override
    public void startCreate(String filePath, String fileName) {
        try {
            document = new Document(DEFAULT_PAGE_SIZE, DEFAULT_MARGIN, DEFAULT_MARGIN, DEFAULT_MARGIN, DEFAULT_MARGIN);
            writer = PdfWriter.getInstance(document, new FileOutputStream(filePath + File.separator + fileName));
            document.open();
        } catch (DocumentException | FileNotFoundException e) {
            handleException(e);
        }
    }

    @Override
    public void addCatalog(String text, TitleLevel level) {
        Font tocEntryFont = FontUtils.getChineseFont(fontSize, false, false, null);
        Paragraph tocEntry = new Paragraph(text, tocEntryFont);
        addElement(tocEntry);
    }

    @Override
    public void addTitle(String title, TitleLevel level) {
        addTitle(title, level, Element.ALIGN_LEFT);
    }

    private Stack<ChapterLevel> chapterStack = new Stack<>();

    private static class ChapterLevel {
        private Section section;
        private int level;

        public ChapterLevel(Section section, int level) {
            this.section = section;
            this.level = level;
        }

        public Section getSection() {
            return section;
        }

        public int getLevel() {
            return level;
        }
    }

    private void addTitle1(String title, TitleLevel level, int align) {
        Font titleFont = FontUtils.getChineseFont(level.getSize(), false, true, null);
        Paragraph titlePara = new Paragraph(title, titleFont);
        titlePara.setAlignment(align);
        Chapter elements = new Chapter(titlePara, level.getLevel());
        addElement(elements);
    }

    private void addTitle(String title, TitleLevel level, int align) {
        Font titleFont = FontUtils.getChineseFont(level.getSize(), false, true, null);
        Paragraph titlePara = new Paragraph(title, titleFont);
        titlePara.setAlignment(align);

        int currentLevel = level.getLevel();

        try {
            if (currentLevel == 1) {
                // 处理H1标题：创建新Chapter并重置堆栈
                Chapter chapter = new Chapter(titlePara, 1);
                chapter.setNumberDepth(0);
                addElement(chapter);
                chapterStack.clear();
                chapterStack.push(new ChapterLevel(chapter, currentLevel));
            } else {
                // 处理H2及以下标题：找到父级并创建Section
                while (!chapterStack.isEmpty() && chapterStack.peek().getLevel() >= currentLevel) {
                    chapterStack.pop();
                }
                if (chapterStack.isEmpty()) {
                    throw new DocumentException("Missing parent chapter for level " + currentLevel);
                }
                ChapterLevel parent = chapterStack.peek();
                Section newSection = parent.getSection().addSection(titlePara);
                addElement(newSection);

                newSection.setNumberDepth(currentLevel - 1);
                chapterStack.push(new ChapterLevel(newSection, currentLevel));
            }
        } catch (DocumentException e) {
            handleException(e);
        }
    }

    @Override
    public void addTitleCenter(String title, TitleLevel level) {
        addTitle(title, level, Element.ALIGN_CENTER);
    }

    @Override
    public void addParagraph(String text, boolean bold, boolean highlight) {
        Font font = FontUtils.getChineseFont(fontSize, bold, highlight, null);
        Paragraph paragraph;
        // 处理高亮背景色（iText 实现方式）
        if (highlight) {
            // 方式1：使用 Chunk 设置背景色（简单文本适用）
            Chunk chunk = new Chunk(text, font);
            chunk.setBackground(BaseColor.YELLOW); // 设置黄色背景
            paragraph = new Paragraph(chunk);

            // 方式2：通过表格单元格模拟背景（复杂内容适用）
            // PdfPTable table = new PdfPTable(1);
            // table.setWidthPercentage(100);
            // PdfPCell cell = new PdfPCell(paragraph);
            // cell.setBackgroundColor(BaseColor.YELLOW);
            // cell.setBorder(Rectangle.NO_BORDER);
            // table.addCell(cell);
            // addElement(table);
            // return; // 提前返回，避免重复添加
        } else {
            paragraph = new Paragraph(text, font);
        }
        paragraph.setFirstLineIndent(fontSize * 2);
        // 设置段落前间距
        paragraph.setSpacingBefore(DEFAULT_PARAGRAPH_SPACING_BEFORE);
        // 设置段落后续间距
        paragraph.setSpacingAfter(DEFAULT_PARAGRAPH_SPACING_AFTER);

        addElement(paragraph);
    }

    @Override
    public void addTable(TableInfo tableInfo) {
        PdfPTable table = createTable(tableInfo);
        Paragraph tableParagraph = new Paragraph();
        tableParagraph.add(table);
        // 设置表格前间距
        tableParagraph.setSpacingBefore(DEFAULT_TABLE_SPACING_BEFORE);
        // 设置表格后间距
        tableParagraph.setSpacingAfter(DEFAULT_TABLE_SPACING_AFTER);
        addElement(tableParagraph);
    }

    private PdfPTable createTable(TableInfo tableInfo) {
        PdfPTable table = new PdfPTable(tableInfo.getColNumb());
        table.setWidthPercentage(100);

        Font font = FontUtils.getChineseFont(fontSize, true, true, null);

        // 表头
        List<String> headers = tableInfo.getHead();
        for (String header : headers) {
            PdfPCell cell = new PdfPCell(new Paragraph(header, font));
            // 设置表头背景颜色为蓝色
            cell.setBackgroundColor(CUSTOM_BLUE);
            table.addCell(cell);
        }

        // 表格内容
        List<List<String>> body = tableInfo.getBody();
        for (List<String> rows : body) {
            for (String cellValue : rows) {
                PdfPCell cell = new PdfPCell(new Paragraph(cellValue, font));
                table.addCell(cell);
            }
        }
        return table;
    }

    @Override
    public void addPageBreak() {
        addElement(Chunk.NEWLINE);
    }

    @Override
    public void export() {
        try {
            if (document != null && document.isOpen()) {
                document.close();
            }
            if (writer != null) {
                writer.close();
            }
        } catch (Exception e) {
            handleException(e);
        }
    }

    private void addElement(Element element) {
        try {
            if (document != null && document.isOpen()) {
                document.add(element);
            }
        } catch (DocumentException e) {
            handleException(e);
        }
    }

    private void handleException(Exception e) {
        // 这里可以添加更复杂的异常处理逻辑，例如日志记录等
        e.printStackTrace();
    }
}